package com.gqz.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gqz.domain.BlogArticleType;
import com.gqz.dto.ArticleTypeDto;
import com.gqz.mapper.BlogArticleMapper;
import com.gqz.mapper.BlogArticleTypeMapper;
import com.gqz.query.BaseQuery;
import com.gqz.service.IBlogArticleTypeService;
import com.gqz.utils.PageList;
import com.gqz.utils.UserTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Service
public class BlogArticleTypeServiceImpl implements IBlogArticleTypeService {

    @Autowired
    private BlogArticleTypeMapper blogArticleTypeMapper;

    @Autowired
    private BlogArticleMapper blogArticleMapper;

    @Override
    public PageList<BlogArticleType> getAllArticleType(BaseQuery query) {

        // 1、使用分页插件分页
        PageHelper.startPage(query.getPageIndex(), query.getPageSize());

        Example example = new Example(BlogArticleType.class);

        if (query.getKeyword() != null) {
            example.or().orLike("typeName", "%"+query.getKeyword()+"%");
        }
        // 2、开始查询
        List<BlogArticleType> blogArticleTypes = blogArticleTypeMapper.selectByExample(example);
        // 3、使用分页工具类封装数据
        PageInfo<BlogArticleType> pageInfo = new PageInfo<>(blogArticleTypes);
        // 4、 使用自定义的分页工具类封装前端需要的数据
        PageList<BlogArticleType> pageList = new PageList<>(pageInfo.getTotal(), pageInfo.getList());
        return pageList;
    }

    @Override
    public List<ArticleTypeDto> getAllArticleType() {
        List<ArticleTypeDto> blogArticleTypes = blogArticleTypeMapper.getAllArticleTypeDto();
        return blogArticleTypes;
    }


    @Override
    public boolean insertArticleType(BlogArticleType articleType, HttpServletRequest request) {
        articleType.setUpdateUserName(UserTools.getCurrentUserRealName(request));
        return blogArticleTypeMapper.insert(articleType) > 0;
    }

    @Override
    public boolean updateArticleType(BlogArticleType articleType, HttpServletRequest request) {
        articleType.setUpdateTime(new Date());
        articleType.setUpdateUserName(UserTools.getCurrentUserRealName(request));
        return blogArticleTypeMapper.updateByPrimaryKey(articleType) > 0;
    }

    @Override
    public boolean batchDeleteArticleType(Long[] ids) {
        blogArticleMapper.batchDeleteArticleByTypeIds(ids);
        return blogArticleTypeMapper.batchDeleteArticleType(ids) > 0;
    }

    @Override
    public boolean deleteArticleType(Long id) {
        blogArticleMapper.batchDeleteArticleByTypeIds(new Long[]{id});
        return blogArticleTypeMapper.deleteByPrimaryKey(id) > 0;
    }
}
